import { ElMessage } from 'element-plus';

import { credit, zhengxinUrl } from '@/config';
import { getItem, ACCESS_TOKEN } from '@/utils/db';
import { clearCache } from '@/utils/auth';
import { encodeserialize } from '@/utils/util';
import { userStore } from '@/store/modules/user';

import { router } from './router';
import { AxiosInstance, AxiosRequestConfig } from 'axios';

export function initAxios(axios: AxiosInstance) {
  axios.defaults.withCredentials = true;
  axios.defaults.timeout = 5000;

  axios.interceptors.request.use(
    (config: AxiosRequestConfig) => {
      const tenantId = userStore.tenantId;
      config.headers = {
        ...config.headers,
        credit,
        'tenant-id': tenantId,
      };

      // config.headers['Authorization'] = `Basic ${btoa(
      //   `${website.clientId}:${website.clientSecret}`
      // )}`;

      const token = getItem(ACCESS_TOKEN);
      if (token) {
        config.headers['Blade-Auth'] = 'bearer ' + token;
      }
      const { url = '' } = config;
      if (url.indexOf(zhengxinUrl as string) > -1) {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        config.headers['credit'] = credit;

        config.transformRequest = data => {
          if (data) {
            return encodeserialize(data);
          } else {
            return data;
          }
        };
      }
      return config;
    },
    err => {
      return Promise.reject(err);
    },
  );

  axios.interceptors.response.use(
    res => {
      const status = res.data.code || res.status;
      const msg = res.data.msg || res.data.error_description || '未知错误';
      if (status !== 200) {
        ElMessage({
          message: msg,
          type: 'warning',
        });
        return Promise.reject(new Error(msg));
      }
      return res;
    },
    error => {
      const { code } = error.response.data;
      if (code === 401) {
        clearCache();
        router.push({ path: '/' });
      } else {
        return error.response;
      }
      return Promise.reject(new Error(error));
    },
  );
}
